# -*- encoding: utf-8 -*-
##############################################################################
##############################################################################

from odoo import models, fields, api
from odoo.tools.translate import _
from odoo.exceptions import ValidationError
from odoo.tools.float_utils import float_round


class stock_picking(models.Model):
    _inherit = 'stock.picking'

    def _create_lots_for_picking(self):
        if self.picking_type_id.use_create_lots:
            for pack_op_lot in self.mapped('pack_operation_ids').mapped('pack_lot_ids'):
                if pack_op_lot.lot_id:
                    # 字段赋值
                    pack_op_lot.lot_id.lot_uom = pack_op_lot.lot_uom.id
                    pack_op_lot.lot_id.lot_uom_ratio = pack_op_lot.lot_uom_ratio

                    pack_op_lot.lot_id.lot_lenth = pack_op_lot.lot_lenth
                    pack_op_lot.lot_id.code = pack_op_lot.code
                    pack_op_lot.lot_id.description = pack_op_lot.description
                    pack_op_lot.lot_id.board_number = pack_op_lot.board_number

        super(stock_picking, self)._create_lots_for_picking()


class stock_pack_operation(models.Model):
    _inherit = 'stock.pack.operation'

    @api.multi
    def action_split_lots(self):
        action_ctx = dict(self.env.context)
        # If it's a returned stock move, we do not want to create a lot
        returned_move = self.linked_move_operation_ids.mapped('move_id').mapped('origin_returned_move_id')
        picking_type = self.picking_id.picking_type_id
        action_ctx.update({
            'serial': self.product_id.tracking == 'serial',
            'only_create': picking_type.use_create_lots and not picking_type.use_existing_lots and not returned_move,
            'picking_type': picking_type.id,
            'create_lots': picking_type.use_create_lots,
            'state_done': self.picking_id.state == 'done',
            'show_reserved': any([lot for lot in self.pack_lot_ids if lot.qty_todo > 0.0])})
        view_id = self.env.ref('stock.view_pack_operation_lot_form').id
        return {
            'name': _('Lot/Serial Number Details'),
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'stock.pack.operation',
            'views': [(view_id, 'form')],
            'view_id': view_id,
            'target': 'new',
            'res_id': self.ids[0],
            'context': action_ctx}
